import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { forkJoin } from 'rxjs';
import { SellPromotionManageService } from '../sell-promotion-manage.service';
import { endOfMonth } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { defalutImg } from 'src/app/comm';
import { CommonService } from '../../../../services-common/common.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-direct-descent-addedit',
  templateUrl: './direct-descent-addedit.component.html',
  styleUrls: ['./direct-descent-addedit.component.scss'],
  providers: [DatePipe]
})
export class DirectDescentAddeditComponent implements OnInit {

  routerParams: any = {};
  fallback: string = defalutImg;
  // formParams
  formParams: any = {
    type: 1, // 活动类型：1、满减型 2、折扣型 3、多件折扣 4、多件立减 5、阶梯满减 6、阶梯折扣
    name: '', // 活动名称
    showCopy: '', // 活动标题
    remark: '', // 备注
    orderLimitMoney: '', // 订单满多少可用，0表示无门槛
    limitSmall: '', // 减免额度 | 折扣力度
    overlayFlag: '', // 倍数减免 0：否，1：是
    limitBig: '', // 最高减免金额
    userType: '', // 适用用户(0-通用、1-C端、2-B端)
    beginTime: '', // 活动开始时间
    endTime: '', // 活动结束时间
    isPlusCoupons: '0', // 是否可以叠加优惠券(0是 1否)
    skinTopImage: '', // 顶部图片 手机端
    skinTopMargin: 0, // 顶部边距 手机端
    skinBgColor: '#FFFFFF', // 背景色 手机端
    skinTopImagePc: '', // 顶部图片 pc端
    skinTopMarginPc: 0, // 顶部边距 pc端
    skinBgColorPc: '#FFFFFF', // 背景色 pc端
    isFilterSort: '', // 筛选排序 0-不开启 1-开启
    goodsFilter: {
      '1': {},
      '2': {},
      '3': {},
      '4': {}
    },
    status: 5, // 状态：1、未开始 2、进行中 3、已结束 4、已停止 5 草稿 6、待审核 7、审核不通过 8删除
  };

  // 活动有效时间
  activityTimes: any = [];
  // 预设日期
  ranges = { '此刻': [new Date(), new Date()] };
  // 优惠叠加 是否可以叠加优惠券(0是 1否)
  superPositions: any = [
    { label: '优惠券', value: 0, checked: true }
  ];

  // 指定分类list
  classifyLists: any = [];
  // 指定品牌list
  brandLists: any = [];
  // 指定分类全选 | 全不选状态
  classifyAllChecked: boolean = false;
  classifyNotChecked: boolean = false;
  // 指定品牌全选 | 全不选状态
  brandAllChecked: boolean = false;
  brandNotChecked: boolean = false;

  // 商品列表 model
  isSelectVisible: boolean = false;
  modelTableForms: any = {
    tableLoading: false,
    name: '', // 搜索商品编号或名称
    page: 1, // 当前页码
    pageSize: 10, // 一页条数
    total: 0
  };
  modelGoodsTable: any = [];
  addGoodsLists: any = []; // 追加可用商品list
  excludeGoodsLists: any = []; // 排除可用商品list
  disabledLists: any = []; // 商品列表禁选项

  // 查看已选商品列表
  isPreiviewVisible: boolean = false;
  preiviewTableData: any = [];
  preiviewTableForm: any = {
    idList: [],
    page: 1,
    pageSize: 10,
    total: 0
  }

  // 适用type 0：追加可用，1：排除可用
  applyType: any;
  // 追加可用list
  addAvailableLists: any = [];
  addAvailableDisabled: boolean = false;
  // 排除可用list
  excludeAvailableLists: any = [];

  // 发布 | 保存 btn loading
  releaseLoading: boolean = false;
  conserveLoading: boolean = false;

  // modelTable****** 勾选
  checked: boolean = false;
  indeterminate: boolean = false;
  listOfCurrentPageData: readonly any[] = []; // 当前展示页面数据
  setOfCheckedId = new Set<number>(); // 已选ids
  setofCheckedArrs: object[] = []; // 已选项数组

  // 多件折扣Table
  discountTable: any = [];

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private modal: NzModalService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: SellPromotionManageService
  ) {
    this.activatedRoute.queryParams.subscribe((res: any) => {
      // console.log('router', res);
      // res.type 0：新增，1：编辑，2：复制
      this.routerParams = res;
    })
  }

  ngOnInit(): void {
    // [指定分类，指定品牌]
    const forkArrs: any = [this.services.queryClassificationListData(), this.services.queryBrandListData()]
    forkJoin(forkArrs).subscribe((res: any) => {
      // 分类
      let classifyItems: any = res[0].data ? this.consversionTree(res[0].data) : [];
      // 品牌
      let brandItems: any = res[1].data.brandList ? res[1].data.brandList.map((item: any) => { return {label: item.name, value: item.id, checked: false} }) : [];

      this.classifyLists =  classifyItems;
      this.brandLists = brandItems;

      if (this.routerParams.id != '-1') {
        this.getActivityDetailData();
      }
    })
  }

  // 查询活动详情
  async getActivityDetailData() {
    try {
      this.message.loading('loading...', {nzDuration: 0});
      const res: any = await this.services.queryPromotionDetailsData({ id: this.routerParams.id, page: 1, pageSize: 1 });
      if (res.code == 0) {
        const { promotionInfo }: any = res.data;
        // 设置值
        this.setValue(promotionInfo);
      } else {
        this.message.error(res.message || '详情获取失败');
      }
      this.message.remove();
    } catch (error: any) {
      this.message.remove();
      this.message.error(error);
    }
  }
  // 编辑设置值
  setValue(promotionInfo: any) {
    this.formParams.type = promotionInfo.type; // 活动类型：1、满减型  2、折扣型  3、多件折扣
    this.formParams.name = promotionInfo.name; // 活动名称
    this.formParams.showCopy = promotionInfo.showCopy; // 活动标题
    this.formParams.remark = promotionInfo.remark; // 活动标题
    this.formParams.orderLimitMoney = String(promotionInfo.orderLimitMoney); // 订单满多少可用，0表示无门槛
    this.formParams.limitSmall = promotionInfo.limitSmall; // 减免额度 | 折扣力度
    this.formParams.overlayFlag = String(promotionInfo.overlayFlag); // 倍数减免 0：否，1：是
    this.formParams.limitBig = promotionInfo.limitBig; // 最高减免金额
    this.formParams.userType = String(promotionInfo.userType); // 适用用户--参与人(0-通用、1-C端、2-B端)
    this.formParams.beginTime = promotionInfo.beginTime; // 活动开始时间
    this.formParams.endTime = promotionInfo.endTime; // 活动开始时间
    this.formParams.goodsFilter = promotionInfo.goodsFilterResult; // 适用商品
    this.formParams.status = promotionInfo.status; // 状态
    this.formParams.isPlusCoupons = promotionInfo.isPlusCoupons; // 优惠叠加

    this.formParams.skinTopImage = promotionInfo.skinTopImage; // 顶部图片 WAP
    this.formParams.skinTopMargin = promotionInfo.skinTopMargin; // 顶部边距 WAP
    this.formParams.skinBgColor = promotionInfo.skinBgColor; // 背景色 WAP
    this.formParams.skinTopImagePc = promotionInfo.skinTopImagePc; // 顶部图片 PC
    this.formParams.skinTopMarginPc = promotionInfo.skinTopMarginPc; // 顶部边距 PC
    this.formParams.skinBgColorPc = promotionInfo.skinBgColorPc; // 背景色 PC
    this.formParams.isFilterSort = !this.commonService.isEmpty(promotionInfo.isFilterSort) ? promotionInfo.isFilterSort : ''; // 筛选排序

    this.superPositions[0].checked = promotionInfo.isPlusCoupons ? false : true; // 优惠叠加Arry勾选设置

    this.activityTimes = [promotionInfo.beginTime, promotionInfo.endTime]; // 有效时间段
    this.discountTable = promotionInfo?.discountContent ? JSON.parse(promotionInfo?.discountContent) : []; // (多件折扣、多件立减、阶梯满减、阶梯折扣)优惠内容Table

    // 指定分类
    if (promotionInfo.goodsFilterResult['1']) {
      let noSelect = promotionInfo.goodsFilterResult['1']['-1']; // 全不选
      let allSelect = promotionInfo.goodsFilterResult['1']['0']; // 全选
      let idArr = promotionInfo.goodsFilterResult['1']['1']; // 已选列表

      if (noSelect) {
        this.classifyNotChecked = true;
      } else if (allSelect) {
        this.classifyAllChecked = true;
        this.classifyLists.forEach((ele: any) => {
          ele.children.forEach((tag: any) => {
            tag.checked = true;
          })
        });
      } else {
        this.classifyLists.forEach((ele: any) => {
          ele.children.forEach((tag: any) => {
            if (idArr.includes(tag.value)) {
              tag.checked = true;
            }
          })
        });
      }
    }

    // 指定品牌
    if (promotionInfo.goodsFilterResult['2']) {
      let noSelect = promotionInfo.goodsFilterResult['2']['-1']; // 全不选
      let allSelect = promotionInfo.goodsFilterResult['2']['0']; // 全选
      let idArr = promotionInfo.goodsFilterResult['2']['1']; // 已选列表

      if (noSelect) {
        this.brandNotChecked = true;
      } else if (allSelect) {
        this.brandAllChecked = true;
        this.brandLists.forEach((ele: any) => {
          ele.checked = true;
        });
      } else {
        this.brandLists.forEach((ele: any) => {
          if (idArr.includes(ele.value)) {
            ele.checked = true;
          }
        });
      }
    }

    // 追加可用商品
    if (promotionInfo.goodsFilterResult['3']) {
      let idArr = promotionInfo.goodsFilterResult['3']['1'] || [];
      if (idArr.length) {
        idArr.forEach((ele: any) => {
          this.addAvailableLists.push({
            id: ele
          })
        });
      }
    }
    // 排除可用商品
    if (promotionInfo.goodsFilterResult['4']) {
      let idArr = promotionInfo.goodsFilterResult['4']['1'] || [];
      if (idArr.length) {
        idArr.forEach((ele: any) => {
          this.excludeAvailableLists.push({
            id: ele
          })
        });
      }
    }
  }

  // 查询商品列表
  async queryGoodsTableData() {
    try {
      let params = {
        name: this.modelTableForms.name,
        typeId: -1,
        status: -1,
        current: this.modelTableForms.page,
        size: this.modelTableForms.pageSize
      }
      this.modelTableForms.tableLoading = true;
      const res: any = await this.services.queryGoodsListData(params);
      this.modelTableForms.tableLoading = false;

      // 设置禁选
      if (this.disabledLists.length) {
        res.data.records.forEach((ele: any) => {
          if (this.disabledLists.includes(ele.id)) {
            ele.disabled = true;
          }
        });
      }

      if (res.code == 0) {
        const { records, total }: any = res.data;

        this.modelGoodsTable = records || [];
        this.modelTableForms.total = total || 0;
      } else {
        this.message.error(res.message || '商品列表获取失败');
      }
    } catch (error: any) {
      this.modelTableForms.tableLoading = false;
      this.message.error(error);
      this.modelGoodsTable = [];
      this.modelTableForms.total = 0;
    }
  }

  // 优惠门槛 | 减免额度验证
  discountLimitChange(num: number) {
    if (this.formParams.orderLimitMoney &&
      this.formParams.limitSmall &&
      this.formParams.orderLimitMoney <= this.formParams.limitSmall) {
      switch (num) {
        case 0:
          // console.log('优惠门槛');
          this.message.warning('优惠门槛值需大于减免额度值');
          this.formParams.orderLimitMoney = '';
          return
        case 1:
          // console.log('减免额度');
          this.message.warning('减免额度值需小于优惠门槛值');
          this.formParams.limitSmall = '';
          return
      }
    }
  }

  /******************************** 适用商品 START ******************************** */
  // 指定分类数据处理tree
  consversionTree(arr: any) {
    return arr.map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = this.consversionTree(item.children);
      }

      if (item.children && item.children.length <= 0) {
        item.checked = false;
      }

      let obj: any = {
        ...item,
        value: item.id,
        label: item.name
      }
      return obj
    })
  }
  // children数组合并
  conversionArrs(arrs: any) {
    let tempArr: any = [];
    if (arrs.length) {
      arrs.map((ele: any) => {
        tempArr = tempArr.concat(ele.children);
      });
    }
    return tempArr;
  }
  // 指定分类全选按钮选中与不选中
  addFieldArr(arr: any, isStr: any) {
    return arr.map((item: any) => {
      if (item.children) {
        item.children = this.addFieldArr(item.children, isStr);
      }
      if (!item.children || item.children.length <= 0) {
        item.checked = isStr;
      }

      let obj: any = {
        ...item
      }
      return obj
    })
  }

  /**
   * 指定分类select
   * @param num 0：全选 | 全不选，1：全不选
   * @returns
   */
  classifyListSelect(num: number) {
    switch (num) {
      case 0:
        if (this.classifyAllChecked) {
          this.classifyLists = this.addFieldArr(this.classifyLists, true);
          if (this.classifyNotChecked) {
            this.classifyNotChecked = false;
          }
        } else {
          this.classifyLists = this.addFieldArr(this.classifyLists, false);
        }
        break
      case 1:
        this.classifyLists = this.addFieldArr(this.classifyLists, false);
        if (this.classifyAllChecked) {
          this.classifyAllChecked = false;
        }
        break
    }

    this.setAppendVal();
  }
  // 指定分类单选
  classifySingleChecked() {
    let tempArrys: any = [];
    this.classifyLists.forEach((ele: any) => {
      let tempBool = ele.children.every((tag: any) => {
        return tag.checked == true;
      })
      tempArrys.push(tempBool);
    });

    // 设置全选按钮状态
    this.classifyAllChecked = !tempArrys.includes(false);
    this.setAppendVal();
  }

  /**
   * 指定品牌select
   * @param num 0：全选 | 全不选，1：全不选
   */
  branListSelect(num: number): void {
    switch (num) {
      case 0:
        if (this.brandAllChecked) {
          this.brandLists = this.brandLists.map((item: any) => ({
            ...item,
            checked: true
          }));
          if (this.brandNotChecked) {
            this.brandNotChecked = false;
          }
        } else {
          this.brandLists = this.brandLists.map((item: any) => ({
            ...item,
            checked: false
          }));
        }
        break
      case 1:
        this.brandLists = this.brandLists.map((item: any) => ({
          ...item,
          checked: false
        }));
        if (this.brandAllChecked) {
          this.brandAllChecked = false;
        }
        break
    }

    this.setAppendVal();
  }
  // 指定品牌单选
  brandSingleChecked(): void {
    if (this.brandLists.every((item: any) => !item.checked)) {
      this.brandAllChecked = false;
    } else if (this.brandLists.every((item: any) => item.checked)) {
      this.brandAllChecked = true;
    } else {
      this.brandAllChecked = false;
    }

    this.setAppendVal();
  }

  /**
   * 选择商品
   * @param num 0：追加可用，1：排除可用
   * @param arry
   * @param disabledArr 禁选项
   */
  async selectGoodsModel(num: number, arry: any, disabledArr: any) {
    this.applyType = num;
    this.setOfCheckedId.clear();

    this.disabledLists = disabledArr.map((item: any) => item.id);
    arry.forEach((ele: any) => {
      this.setOfCheckedId.add(ele.id);
    });
    this.setofCheckedArrs = JSON.parse(JSON.stringify(arry));

    this.modelTableForms.page = 1;
    this.queryGoodsTableData();
    this.isSelectVisible = true;
  }
  /**
   * 查看商品
   * @param num 0：追加可用，1：排除可用
   */
  async previewGoodsModel(num: Number) {
    this.applyType = num;
    this.preiviewTableData = [];
    this.preiviewTableForm.idList = [];

    if (num == 0) {
      this.preiviewTableForm.idList = this.addAvailableLists.map((item: any) => item.id);
    } else {
      this.preiviewTableForm.idList = this.excludeAvailableLists.map((item: any) => item.id);
    }
    this.preiviewTableForm.page = 1;
    this.getIdsGoodsListData();

    this.isPreiviewVisible = true;
  }
  // 根据商品ids查询商品列表
  async getIdsGoodsListData() {
    let params = {
      idList: this.preiviewTableForm.idList,
      pageNum: this.preiviewTableForm.page,
      pageSize: this.preiviewTableForm.pageSize
    }
    const res: any = await this.services.queryIdsGoodsListData(params);
    this.preiviewTableData = res.data?.records || [];
    this.preiviewTableForm.total = res.data?.total || 0;
  }

  handleCancel(): void {
    this.isSelectVisible = false;
  }

  // 查询商品列表
  queryTbale() {
    this.modelTableForms.page = 1;
    this.queryGoodsTableData();
  }

  // 关联已选商品
  relationData() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择商品');
      return
    }

    this.isSelectVisible = false;
    // applyType 0：追加可用，1：排除可用
    if (this.applyType == 0) {
      this.addAvailableLists = JSON.parse(JSON.stringify(this.setofCheckedArrs));
    } else {
      this.excludeAvailableLists = JSON.parse(JSON.stringify(this.setofCheckedArrs));
    }
  }

  // 查看已选商品
  handleCancelTwo() {
    this.isPreiviewVisible = false;
  }

  // 删除已关联商品
  deleteItem(item: any, index: number) {
    let deleteIndex = this.preiviewTableForm.idList.findIndex((ele: any) => ele == item.id);
    this.preiviewTableForm.idList.splice(deleteIndex, 1);
    // applyType 0：追加可用，1：排除可用
    if (this.applyType == 0) {
      this.addAvailableLists = this.preiviewTableForm.idList.map((item: any) =>{ return { id: item } });
    } else {
      this.excludeAvailableLists = this.preiviewTableForm.idList.map((item: any) =>{ return { id: item } });
    }
    this.getIdsGoodsListData();

    if (this.preiviewTableForm.page > 1 && !this.preiviewTableData.length) {
      this.preiviewTableForm.page = 1;
      this.getIdsGoodsListData();
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.modelTableForms.page = index;
    this.queryGoodsTableData();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.modelTableForms.page = 1;
    this.modelTableForms.pageSize = sizeNum;

    this.queryGoodsTableData();
  }

  // 当前页码改变时的回调函数（----查看model----）
  onPageIndexChangeTwo(index: number) {
    this.preiviewTableForm.page = index;
    this.getIdsGoodsListData();
  }
  // 页数改变时回调（----查看model----）
  onPageSizeChangeTwo(sizeNum: number) {
    this.preiviewTableForm.page = 1;
    this.preiviewTableForm.pageSize = sizeNum;

    this.getIdsGoodsListData();
  }
  /******************************** 适用商品 END ******************************** */

  /**********************************************model表格勾选操作 START**********************************************/
  // 勾选设置
  updateCheckedSet(id: number, checked: boolean, item?: any): void {
    if (checked && !item.disabled) {
      this.setOfCheckedId.add(id);

      if (this.setofCheckedArrs.length > 0) {
        let isHas = this.setofCheckedArrs.some((tag: any) => { return tag.id == id });
        if (!isHas) {
          this.setofCheckedArrs.push(item);
        }
      } else {
        this.setofCheckedArrs.push(item);
      }
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setofCheckedArrs.findIndex((tag: any) => { return tag.id == id });
      this.setofCheckedArrs.splice(delIndex, 1);
    }
  }
  // 单选
  onItemChecked(id: number, checked: boolean, item?: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }
  // 全选
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.filter(({ disabled }) => !disabled).forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }
  // 当前页面展示数据改变的回调函数
  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }
  // 全选按钮状态
  refreshCheckedStatus(): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(({ disabled }) => !disabled);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
  /**********************************************model表格勾选操作 END**********************************************/

  // 类型cahnge
  typeRadioChange(type: any) {
    this.formParams.limitSmall = '' // 减免额度 | 折扣力度
    this.formParams.overlayFlag = '' // 倍数减免 0：否，1：是
    this.formParams.limitBig = '' // 最高减免金额
    this.discountTable = []; // 多件折扣Table
    this.formParams.orderLimitMoney = ''; // 优惠门槛

    if (type === 3) {
      this.formParams.orderLimitMoney = '0'; // 优惠门槛
    }
  }
  // 时间选择change
  timeChange(result: any) {
    this.formParams.beginTime = result.length ? this.datePipe.transform(new Date(result[0]), 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams.endTime = result.length ? this.datePipe.transform(new Date(result[1]), 'yyyy-MM-dd HH:mm:ss') : '';
  }

  // 确定发布
  releaseData() {
    if (!this.verifData()) {
      return
    }
    this.modal.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: '<b>确认发布?</b>',
      nzOnOk: () => {
        this.subData(0);
      }
    });
  }

  /**
   * 提交
   * num 0：发布，1：保存
   * formParams.status 状态：1、未开始 2、进行中 3、已结束 4、已停止 5 草稿 6、待审核 7、审核不通过 8删除
   */
  async subData(num: number) {
    this.applicableTreatment();
    if (!this.verifData()) {
      return
    }
    // 新增 | 复制时状态设置；编辑时状态用详情中的状态
    if (num == 0) {
      this.formParams.status = 1;
    } else {
      if (this.routerParams.type == 0 || this.routerParams.type == 2) {
        this.formParams.status = 5;
      }
    }

    let params = {
      ...this.formParams,
      discountContent: JSON.stringify(this.discountTable)
    }
    for (let key in params) {
      if (this.commonService.isEmpty(params[key])) {
        delete params[key];
      }
    }
    // console.log('subdata', params);
    // return

    let res: any = null;
    if (this.routerParams.type == 0 || this.routerParams.type == 2) {
      // newly added
      res = await this.services.addSalesPromotionData(params);
      if (res.code == 0) {
        this.message.success('新增成功');
        this.router.navigate(['/sell/descentManage']);
      } else {
        this.message.error(res.message || '新增失败');
      }
    } else {
      // edit
      params.id = this.routerParams.id;
      res = await this.services.updateSalesPromotionData(params);
      if (res.code == 0) {
        this.message.success('编辑成功');
        this.router.navigate(['/sell/descentManage']);
      } else {
        this.message.error(res.message || '编辑失败');
      }
    }
  }

  // Button返回
  goBack() {
    history.back();
  }

  // 适用商品数据处理
  applicableTreatment() {
    // 指定分类 0为全部,-1为全不选
    let tempClassifyArr: any[] = this.conversionArrs(this.classifyLists).filter((item: any) => { return item.checked }).map((tag: any) => { return tag.value });
    this.formParams.goodsFilter['1'] = {};
    if (this.classifyAllChecked) {
      this.formParams.goodsFilter['1']['0'] = tempClassifyArr;
    } else if (this.classifyNotChecked) {
      this.formParams.goodsFilter['1']['-1'] = tempClassifyArr;
    } else {
      this.formParams.goodsFilter['1']['1'] = tempClassifyArr;
    }

    // 指定品牌 0为全部,-1为全不选
    let tempBrandArr: any[] = this.brandLists.filter((item: any) => { return item.checked }).map((tag: any) => { return tag.value });
    this.formParams.goodsFilter['2'] = {};
    if (this.brandAllChecked) {
      this.formParams.goodsFilter['2']['0'] = tempBrandArr;
    } else if (this.brandNotChecked) {
      this.formParams.goodsFilter['2']['-1'] = tempBrandArr;
    } else {
      this.formParams.goodsFilter['2']['1'] = tempBrandArr;
    }

    // 追加可用 0为空,1为有选值
    let tempAddArr: any[] = this.addAvailableLists.map((tag: any) => { return tag.id });
    this.formParams.goodsFilter['3'] = {};
    if (!this.addAvailableLists.length) {
      this.formParams.goodsFilter['3']['0'] = tempAddArr;
    } else {
      this.formParams.goodsFilter['3']['1'] = tempAddArr;
    }

    // 追加可用 0为空,1为有选值
    let tempExcludeArr: any[] = this.excludeAvailableLists.map((tag: any) => { return tag.id });
    this.formParams.goodsFilter['4'] = {};
    if (!this.excludeAvailableLists.length) {
      this.formParams.goodsFilter['4']['0'] = tempExcludeArr;
    } else {
      this.formParams.goodsFilter['4']['1'] = tempExcludeArr;
    }
  }

  /**
   * 设置追加可用商品
   * 指定分类、指定品牌都全选，可追加商品项清空且不可选
   */
  setAppendVal() {
    if (this.classifyAllChecked && this.brandAllChecked) {
      this.addAvailableLists = [];
      this.addAvailableDisabled = true;
    } else {
      this.addAvailableDisabled = false;
    }
  }

  // 优惠叠加change
  changeSuper(value: string[]) {
    // console.log(value);
    this.formParams.isPlusCoupons = value.length ? '0' : '1';
  }

  /**
   * ----------------------------------------------------------------
   * 多件折扣 or 多件立减 or 阶梯满减 or 阶梯折扣
   * ----------------------------------------------------------------
   */
  addDiscountItem(type: number) {
    if (this.verifDiscountTable(type)) {
      this.message.warning('优惠内容已添加项中存在未填写项，请先完善信息');
      return
    }
    if (this.discountTable.length < 5) {
      // (多件折扣:3 & 阶梯折扣:6) | (多件立减:4 & 阶梯满减:5)
      const objs: any = {
        3: {number: '', discountRate: '', maxReduction: ''},
        4: {number: '', reduction: ''},
        5: {orderLimitMoney: '', reduction: ''},
        6: {orderLimitMoney: '', discountRate: '', maxReduction: ''}
      }
      this.discountTable = [
        ...this.discountTable,
        objs[this.formParams.type]
      ]
    }
  }
  
  deleteDiscountItem(index: number) {
    this.discountTable = this.discountTable.filter((d: any, i: number) => i !== index);
  }

  // 提交验证
  verifData() {
    // 指定分类已选
    let tempClassifyArr: any[] = this.conversionArrs(this.classifyLists).filter((item: any) => { return item.checked }).map((tag: any) => { return tag.value });
    // 指定品牌已选
    let tempBrandArr: any[] = this.brandLists.filter((item: any) => { return item.checked }).map((tag: any) => { return tag.value });

    if (!this.formParams.name) {
      this.message.warning('请输入活动名称');
      return false;
    } else if (!this.formParams.showCopy) {
      this.message.warning('请输入活动标题');
      return false;
    } else if ([1, 2].includes(this.formParams.type) && !this.formParams.orderLimitMoney) {
      this.message.warning('请输入优惠门槛值');
      return false;
    } else if (this.formParams.type == 1 && !this.formParams.limitSmall) {
      this.message.warning('请输入减免额度');
      return false;
    } else if (this.formParams.type == 1 && !this.formParams.overlayFlag) {
      this.message.warning('请选择倍数减免');
      return false;
    } else if (this.formParams.type == 2 && !this.formParams.limitSmall) {
      this.message.warning('请输入折扣力度');
      return false;
    } else if (this.formParams.type == 2 && !this.formParams.limitBig) {
      this.message.warning('请输入最高减免金额');
      return false;
    } else if ([3, 4, 5, 6].includes(this.formParams.type) && !this.discountTable.length) {
      this.message.warning('请先添加优惠内容');
      return false;
    } else if ([3, 4, 5, 6].includes(this.formParams.type) && this.verifDiscountTable(this.formParams.type)) {
      this.message.warning('优惠内容存在未填写项');
      return false;
    } else if (this.formParams.userType == '') {
      this.message.warning('请选择参与人限制');
      return false;
    } else if (!this.formParams.beginTime || !this.formParams.endTime) {
      this.message.warning('请选择活动生效时间');
      return false;
    } else if (!this.formParams.skinBgColor) {
      this.message.warning('请输入手机端背景色');
      return false;
    } else if (!this.formParams.skinTopImage) {
      this.message.warning('请选择手机端顶部图片');
      return false;
    } else if (!this.formParams.skinTopImagePc) {
      this.message.warning('请选择PC端背景色');
      return false;
    } else if (!this.formParams.skinBgColorPc) {
      this.message.warning('请选择PC端顶部图片');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.isFilterSort)) {
      this.message.warning('请选择筛选排序');
      return false;
    } else if (!tempClassifyArr.length && !this.classifyAllChecked && !this.classifyNotChecked) {
      this.message.warning('请选择指定分类');
      return false;
    } else if (!tempBrandArr.length && !this.brandAllChecked && !this.brandNotChecked) {
      this.message.warning('请选择指定品牌');
      return false;
    } else {
      return true;
    }
  }

  // 判断对象是否存在空值
  judgeObjNullValue(obj: any) {
    let flag = false;
    for (let key in obj) {
      if (this.commonService.isEmpty(obj[key])) {
        flag = true;
      }
    }

    return flag;
  }

  // 优惠内容table验证
  verifDiscountTable(type: number) {
    // (多件折扣:3 & 阶梯折扣:6) | (多件立减:4 & 阶梯满减:5)
    let tempBool = this.discountTable.some((item: any) => {
      return this.judgeObjNullValue(item)
    })

    return tempBool;
  }

  limitMinInput(index: number) {
    let minNum = 1;
    if (this.discountTable.length > 1 && index !== 0) {
      // 注: keyStr 件数 和 金额 字段不同
      let keyStr = [3, 4].includes(this.formParams.type) ? 'number' : 'orderLimitMoney';
      let preNum = this.discountTable[index - 1][keyStr];
      minNum = preNum ? preNum + 1 : 1;
    }
    return minNum;
  }

  limitMaxInput(index: number) {
    let maxNum = Infinity;
    if (this.discountTable.length > 1 && index !== this.discountTable.length - 1) {
      // 注: keyStr 件数 和 金额 字段不同
      let keyStr = [3, 4].includes(this.formParams.type) ? 'number' : 'orderLimitMoney';
      let nextNum = this.discountTable[index + 1][keyStr];
      maxNum = nextNum ? nextNum - 1 : Infinity;
    }
    return maxNum;
  }
}
